package com.tutu.controller.backend;

import com.tutu.common.DataTableFactory;
import com.tutu.controller.common.CommonController;
import com.tutu.entity.Article;
import com.tutu.service.ArticleService;
import com.tutu.utils.ImageUtils;
import com.tutu.utils.WebUtil;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 富文本内容管理
 */
@Controller
@RequestMapping(value = "backend/article")
public class ArticleController extends CommonController {

    @Autowired
    ArticleService articleService;

    @RequestMapping(value = "/index")
    public String index() {
        return "backend/article/list";
    }

    @RequestMapping(value = "/info")
    public String info(Model model, Integer id) {
        model.addAttribute("article", articleService.getInfoById(id));

        return "backend/article/info";
    }

    @RequestMapping("/list")
    public void list(HttpServletResponse response, Integer type, String keyWord, Integer draw, Integer start, Integer length) {
        int pageNum = getPageNum(start, length);

        Map<String, Object> result = DataTableFactory.fitting(draw, articleService.pageByParams(type, keyWord, pageNum, length));

        WebUtil.printJson(response, result);
    }

    @RequestMapping("/save")
    @ResponseBody
    public Map<String, Object> save(HttpServletRequest request, Integer id, Integer type, String avatar, String title, String content) {
        return articleService.saveInfo(request, id, type, avatar, title, content);
    }

    @RequestMapping("/del")
    @ResponseBody
    public Map<String, Object> del(HttpServletRequest request, Integer id) {
        return articleService.deleteById(request, id);
    }

    /* 2. 图片上传（TinyMCE 自动调用） */
    @RequestMapping("/upload/img")
    @ResponseBody
    public Map<String, Object> uploadImage(MultipartRequest multipartRequest) {
        Map<String, Object> map = new HashMap<>();

        map.put("location", ImageUtils.saveImage(multipartRequest).getUrl());

        return map;   // 必须返回 {location:"http://xxx.jpg"}
    }

    /* 3. 接收文章（表单方式） */
    @RequestMapping("/submit")
    @ResponseBody
    public Map<String, String> submit(Article article, Model model) {
        // XSS 清洗
        String safe = Jsoup.clean(article.getContent(), Safelist.basicWithImages());

        model.addAttribute("title", article.getTitle());
        model.addAttribute("safeContent", safe);

        return new HashMap<>();
    }
}
